package io;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.text.html.HTMLDocument;

import model.Batch;
import model.Card;
import model.Lesson;
import model.Batch.BatchType;
import model.Lesson.RepeatMode;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * Imports the lessons from pauker (Lesson version 1.7).
 * http://pauker.sourceforge.net/
 * 
 * @author sloth42
 * 
 */
public class PaukerImporter {

	/**
	 * Import the specified pauker file
	 * @param fileToImport pauker file
	 * @return a uniPauker lesson
	 */
	public Lesson importPaukerLesson(File fileToImport) {
		try {

			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(fileToImport);
			Element root = doc.getRootElement();

			String description = root.getChild("Description").getTextTrim();

			Lesson importedLesson = new Lesson(RepeatMode.REMEMBER, false,
					description);

			List<Element> allBatches = root.getChildren("Batch");

			Batch tempBatch;
			int batchNumber = 0;
			for (Element batch : allBatches) {
				if (batchNumber == 0) {
					tempBatch = importedLesson.getNotLearnedBatch();
				} else {
					tempBatch = new Batch(BatchType.LONG_TERM);
				}

				List<Element> children = batch.getChildren("Card");
				List<Element> cards = children;
				for (Element card : cards) {
					Element front = card.getChild("FrontSide").getChild("Text");
					String reverse = card.getChild("ReverseSide").getChild(
							"Text").getTextTrim();
					// TODO convert String to Document
					javax.swing.text.Document docfront = new HTMLDocument();
					javax.swing.text.Document docreverse = new HTMLDocument();
					
					tempBatch.addCard(new Card(docfront, docreverse));
				}
				importedLesson.addLongTermBatch(tempBatch);
			}
			return importedLesson;
			// TODO Exception Handling
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return null;
	}

}
